package rz.dmc.effect;

import java.util.ArrayList;


import rz.dmc.R;
import rz.dmc.util.RZSticker;
import rz.dmc.util.StickerInfo;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.FloatMath;
import android.view.MotionEvent;
import android.view.View;


public class __RZStickerView extends View
{
	private static final int		TOUCH_MODE_NONE = 0;
	private static final int		TOUCH_MODE_DRAG = 1;
	private static final int		TOUCH_MODE_ZOOM = 2;

	private ArrayList<StickerInfo>	stickerInfoList = new ArrayList<StickerInfo>();
	private ArrayList<RZSticker>	stickerList = new ArrayList<RZSticker>();
	private Bitmap					currentBitmap = null;
	
	private float					X;
	private float					Y;
	private float					width = -1;
	private float					height = -1;
    private float					offsetX;			// 처음 이미지를 선택했을 때, 이미지의 X,Y 값과 클릭 지점 간의 거리
    private float					offsetY;
    
    private float					oldDist;			// 핀치시 두좌표간의 거리 저장
    private float					newDist;

    private int					posX1;				// 드래그시 좌표 저장
    private int					posX2;
    private int					posY1;
    private int					posY2;
 
	private int					touchMode = TOUCH_MODE_NONE;
	     
    

	
	public __RZStickerView(Context context, AttributeSet attrs)
	{
		super(context, attrs);

		this.setBackgroundColor(Color.MAGENTA);
		
		int resourceID = R.drawable.girl;
		Bitmap tempBitmap = BitmapFactory.decodeResource(getResources(), resourceID);
		tempBitmap = Bitmap.createScaledBitmap(tempBitmap, 400, 600, true);
		
		addSticker(tempBitmap, 0, 0);
	}
	
	
	
	//---------------------------------------------------------------------
	// TODO Draw!
	//---------------------------------------------------------------------
	public void addSticker(Bitmap bitmap, int x, int y)
	{
		this.X = x;
		this.Y = y;
		this.width = bitmap.getWidth();
		this.height = bitmap.getHeight();
		
		StickerInfo imageInfo = new StickerInfo();
		imageInfo.image = bitmap;
		imageInfo.rect = getRect();

		stickerInfoList.add(imageInfo);
		
		this.invalidate();
	}
	
	public void addSticker(RZSticker sticker)
	{
		sticker.view.setOnTouchListener(onTouchListener);
		
		stickerList.add(sticker);
	}
	
	public Rect getRect()
	{
		Rect rect = new Rect();
		rect.set((int)X,(int)Y, (int)(X+width), (int)(Y+height));
		
		return rect;
	}
	
	@Override
	protected void onDraw(Canvas canvas)
	{
		super.onDraw(canvas);

		for (StickerInfo stickerInfo : stickerInfoList)
		{
			canvas.drawBitmap(stickerInfo.image, null, stickerInfo.rect, null);
		}
		
		// 실시간 화면 캡쳐
//		screenCapture(canvas);
	}
	
	/**
	 * 화면 캡쳐
	 * @param canvas
	 */
	public void screenCapture(Canvas canvas)
	{
		// 미디어 컨트롤러가 보이면 캡쳐 안 함
		currentBitmap = Bitmap.createBitmap(canvas.getWidth(), canvas.getHeight(), Bitmap.Config.ARGB_8888);
		canvas.setBitmap(currentBitmap);
    }

	

	//---------------------------------------------------------------------
	// TODO 터치 이벤트 관련
	//---------------------------------------------------------------------
	private OnTouchListener onTouchListener = new OnTouchListener()
	{
		@Override
		public boolean onTouch(View v, MotionEvent event)
		{
			int action = event.getAction();
			
			switch (action & MotionEvent.ACTION_MASK)
			{
				case MotionEvent.ACTION_DOWN:
				{
					//손가락 터치 위치가 이미지 안에 있으면 DragMode가 시작된다.
					if (InObject(event.getX(), event.getY()))
					{
	                    posX1 = (int) event.getX();
	                    posY1 = (int) event.getY();
	                    offsetX = posX1 - X;
	                    offsetY = posY1 - Y;
	                     
	                    touchMode = TOUCH_MODE_DRAG;
					}
				}
					break;
					
				case MotionEvent.ACTION_MOVE:
				{
	                if (touchMode == TOUCH_MODE_DRAG)			// 드래그 중이면, 이미지의 X, Y값을 변환시키면서 위치 이동. 
	                {   
	                    X = posX2 - offsetX;
	                    Y = posY2 - offsetY;
	                    posX2 = (int) event.getX();
	                    posY2 = (int) event.getY();
	                    
	                    if (Math.abs(posX2-posX1) > 20 || Math.abs(posY2-posY1) > 20) 
	                    {
	                        posX1 = posX2;
	                        posY1 = posY2;
	                    }
	 
	                } 
	                else if (touchMode == TOUCH_MODE_ZOOM)		// 핀치줌 중이면, 이미지의 거리를 계산해서 확대를 한다. 
	                {    
	                    newDist = spacing(event);
	                    
	                    if (newDist - oldDist > 20)				// zoom in 
	                    {  
	                         float scale = FloatMath.sqrt(((newDist-oldDist)*(newDist-oldDist))/(height*height + width * width));
	                         Y=Y-(height*scale/2);
	                         X=X-(width*scale/2);
	                                  
	                         height = height*(1+scale);
	                         width = width*(1+scale);
	                         
	                         oldDist = newDist;
	                         
	                     } 
	                    else if (oldDist - newDist > 20)		// zoom out 
	                    {  
	                         float scale = FloatMath.sqrt(((newDist-oldDist)*(newDist-oldDist))/(height*height + width * width));
	                         scale=0-scale;
	                         Y=Y-(height*scale/2);
	                         X=X-(width*scale/2);
	                                  
	                         height = height*(1+scale);
	                         width = width*(1+scale);
	                         
	                         oldDist = newDist;
	                    }
	                }
				}
	                break;

				case MotionEvent.ACTION_UP:    // 첫번째 손가락을 떼었을 경우
				case MotionEvent.ACTION_POINTER_UP:  // 두번째 손가락을 떼었을 경우
					touchMode = TOUCH_MODE_NONE;
					break;

				case MotionEvent.ACTION_POINTER_DOWN:
				{
					//두번째 손가락 터치(손가락 2개를 인식하였기 때문에 핀치 줌으로 판별)
					touchMode = TOUCH_MODE_ZOOM;
					
					newDist = spacing(event);
					oldDist = spacing(event);
				}
					break;

				default:
					return false;
			}
			
			
			return true;
		}
	};
	
	public boolean InObject(float eventX, float eventY)
	{
        if (eventX < X + width + 30 
        		&& eventX > X - 30 
        		&& eventY < Y + height + 30 
        		&& eventY > Y - 30)
        {
            return true;
        }
        
        return false;
    }
	
	private float spacing(MotionEvent event) 
	{
		float x = event.getX(0) - event.getX(1);
		float y = event.getY(0) - event.getY(1);

		return FloatMath.sqrt(x * x + y * y);
    }
}

